package com.juku2024.juku

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.juku2024.juku.base.BaseActivity
import com.wanban.adutils.AdUtils
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.db.bean.AdContent
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.utils.OpenAdTools
import com.wanban.adutils.utils.VideoInterstitialAdTools
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.NetworkUtils
import com.juku2024.juku.tools.SPUtil
import com.juku2024.juku.viewmodel.SplashViewModel
import com.juku2024.juku.widget.LoadingView

class OpenActivity: BaseActivity() {

    private lateinit var loadingView: LoadingView
    
    private val viewModel by lazy { getViewModel(SplashViewModel::class.java) }
    override fun getLayoutResId(): Int {
        return R.layout.activity_splash
    }

    override fun initView() {
        super.initView()
        loadingView = findViewById(R.id.loadingView_open)
    }

    override fun init(savedInstanceState: Bundle?) {
        BaseApplication.reset()
        loadingView.showLoading()
        // 初始化Iron Source广告
        AdUtils.initIronSource(this, AppUtils.getIronSourceAppKey(this))
        // 开始验证app
        doHttpLogin()
    }

    private fun doHttpLogin() {
        viewModel.checkApp(object : OnRetrofitResultListener<Boolean> {
            override fun onSuccess(t: Boolean) {
                if (isActivityNotActive()) return
                // 请求广告
                doHttpAdList()
            }

            override fun onFailed(msg: String) {
                if (isActivityNotActive()) return
                // 请求广告
                doHttpAdList()
            }
        })
    }


    private fun doHttpAdList() {
        if (!NetworkUtils.isNetworkConnected()) {
            toMain()
            return
        }
        viewModel.getAdList(object : OnRetrofitResultListener<List<AdContent>> {
            override fun onSuccess(t: List<AdContent>) {
                if (isActivityNotActive()) return
                if (t.isEmpty()) {
                    toMain()
                    return
                }
                // 预加载视频广告
                VideoInterstitialAdTools.loadAd(this@OpenActivity)
                // 继续查看是否有开屏广告
                val openAdContent = t.firstOrNull { it.adId == AdConstants.AD_ID_OPEN_AD_V2 }
                if (openAdContent == null || openAdContent.adInfo.isNullOrEmpty()) {
                    // 没有开屏或者Reopen广告
                    toMain()
                    return
                }
                // 加载开屏广告
                OpenAdTools.loadAd(this@OpenActivity, openAdContent.adId, object : OnLoadAdCallback() {

                    override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                        super.onAdLoaded(ad, *tag)
                        if (isActivityNotActive()) return
                        toMain()
                    }

                    override fun onAdLoadFailed(errorCode: Int) {
                        super.onAdLoadFailed(errorCode)
                        if (isActivityNotActive()) return
                        OpenAdTools.release()
                        toMain()
                    }
                })
            }

            override fun onFailed(msg: String) {
                if (isActivityNotActive()) return
                toMain()
            }
        })
    }


    private fun toMain() {
        try {
            val data = intent?.extras
            val intent = if (data == null) {
                Intent(this, MainActivity::class.java)
            } else {
                val videoIdStr = data.getString(Constants.KEY_NOTIFICATION_VIDEO_ID)
                if (TextUtils.isEmpty(videoIdStr)) {
                    LogC.d("启动页收到云消息，但是没有videoId, 当做废弃通知处理...")
                    Intent(this, MainActivity::class.java)
                } else {
                    val videoId: Long = videoIdStr?.toLongOrNull() ?: 0L
                    if (videoId <= 0L) {
                        LogC.d("启动页收到云消息，但videoId <= 0, 当做废弃通知处理...")
                        Intent(this, MainActivity::class.java)
                    } else {
                        val temp = Intent(this, VideoDetailActivity::class.java)
                        temp.putExtra(Constants.AROUTER_KEY_VIDEO_ID, videoId)
                    }
                }
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        } finally {
            finish()
        }
    }



}